'use strict';

const http = require('http');
const url = require('url');
const querystring = require('querystring');
const crypto = require('crypto');
const fs = require('fs');
const ejs = require('ejs');

const TOKEN = 'gaojian08';

const APPID = 'wx7c46e5afd6e38308';
const APPSECRET = 'd5670ab8d491ee35506b78b3376db44b';

http.createServer((req, res) => {
  const accept = req.headers.accept;
  // 如果不是微信客户端直接返回
  if (!/micromessenger|webbrowser/img.test(req.headers['user-agent'].toLowerCase())) {
    res.end('<h1>Hello World.</h1>');
    return true;
  }

  if (/^\*\/\*/img.test(accept)) {
    // console.log(Object.keys(req));
    const _query = url.parse(req.url).query;
    const query = querystring.parse(_query);
    const signature = query.signature;
    const echostr = query.echostr;
    const timestamp = query.timestamp;
    const nonce = query.nonce;

    // 拼成数组，字典排序，再拼接
    const tmpStr = [TOKEN, timestamp, nonce].sort().reduce((prev, cur) => prev + cur);

    // sha1加密
    const sha1 = crypto.createHash('sha1');
    const sha1_result = sha1.update(tmpStr).digest('hex');

    // 如果是来自微信的请求就返回echostr
    if (sha1_result === signature) {
      res.end(echostr);
    }
  } else if (/text\/html/img.test(accept)) {

    const stream = fs.createReadStream('./index.ejs');

    stream.setEncoding('utf8');

    let data = '';
    stream.on('data', thunk => {
      data += thunk || '';
    });

    stream.on('end', function () {
      res.end(ejs.render(data, {
        appId: APPID,
        timestamp: '2',
        nonceStr: '3',
        signature: '4'
      }));
    });

  } else {
    res.end('loading...');
  }
}).listen(8888, () => {
  console.log(`[server] start at 8888`);
});
